package com.xh.one2one.knowledgeSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.one2one.knowledgeSystem.bean.dto.KnowledgeElementDto;
import com.xh.one2one.knowledgeSystem.bean.request.KnowledgeElementRequest;
import com.xh.one2one.knowledgeSystem.model.KnowledgeElement;
import com.xh.one2one.knowledgeSystem.dao.KnowledgeElementMapper;
import com.xh.one2one.knowledgeSystem.model.KnowledgeManager;
import com.xh.one2one.knowledgeSystem.service.IKnowledgeElementService;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.one2one.knowledgeSystem.service.IKnowledgeManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 知识元体系 服务实现类
 * </p>
 *
 * @author tw
 * @since 2020-12-22
 */
@Service
public class KnowledgeElementServiceImpl extends BaseServiceImpl<KnowledgeElementMapper, KnowledgeElement> implements IKnowledgeElementService {

    @Autowired
    private IKnowledgeManagerService knowledgeManagerService;

    @Override
    public XhPage queryKnowledgeElementPage(XhPage page, KnowledgeElementRequest bean) {
        QueryWrapper qw=new QueryWrapper<KnowledgeElement>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page,qw);
    }

    @Override
    public List queryKnowledgeElement(KnowledgeElementRequest bean) {
        QueryWrapper qw=new QueryWrapper<KnowledgeElement>();
        //拼装条件
        qw=prepareParams(bean, qw);
        if(!StringUtils.isEmpty(bean.getStageId())){
            qw.eq("stage_id",bean.getStageId());
        }
        if(!StringUtils.isEmpty(bean.getSubjectId())){
            qw.eq("subject_id",bean.getSubjectId());
        }
        if(StringUtils.isEmpty(bean.getPid())){
            qw.eq("pid", "0");
        }else{
            qw.eq("pid",bean.getPid());
        }
        if(!StringUtils.isEmpty(bean.getName())){
            qw.like("name",bean.getName());
        }
        qw.orderByAsc("sort_num");
        return this.dao.selectList(qw);
    }

    @Override
    @Transactional
    public void updateSort(List<KnowledgeElementRequest> list) {
        for (int i = 0; i < list.size(); i++) {
            KnowledgeElementRequest knowledgeElementRequest = list.get(i);
            KnowledgeElement knowledgeElement = new KnowledgeElement();
            knowledgeElement.setId(knowledgeElementRequest.getId());
            knowledgeElement.setPid(knowledgeElementRequest.getPid());
            knowledgeElement.setSortNum(i+1);
            this.dao.updateById(knowledgeElement);
        }
    }

    @Override
    @Transactional
    public void save(List<KnowledgeElementRequest> list) {
       saveKnowledgeElement(list, null,"0");
    }

    private void  saveKnowledgeElement(List<KnowledgeElementRequest> list,String subjectId,String pid){
        Integer startIndex = -1;

        for (int i = 0; i < list.size(); i++) {
            KnowledgeElementRequest knowledgeElementRequest = list.get(i);
            //配置学科
            if(StringUtils.isEmpty(subjectId)){
                subjectId = knowledgeElementRequest.getSubjectId();
            }

            KnowledgeElement knowledgeElement =new KnowledgeElement();
            if(!StringUtils.isEmpty(pid)){
                knowledgeElement.setPid(pid);
            }
            //查询排序位置
            if(startIndex < 0 ){
                startIndex = getMaxSortNumByPid(subjectId, pid);
            }

            knowledgeElement.setSortNum(startIndex + i + 1);
            knowledgeElement.setSubjectId(subjectId);
            knowledgeElement.setName(knowledgeElementRequest.getName());

            super.insert(knowledgeElement);

            if(!CollectionUtils.isEmpty(knowledgeElementRequest.getChilds())){
               saveKnowledgeElement(knowledgeElementRequest.getChilds(),subjectId,knowledgeElement.getId());
            }
        }
    }

    private  Integer getMaxSortNumByPid(String subjectId,String pid){
        QueryWrapper qw=new QueryWrapper<KnowledgeElement>();
        qw.eq("pid", pid);
        qw.eq("subject_id", subjectId);
        qw.last("limit 1");
        qw.orderByDesc("sort_num");
        KnowledgeElementDto knowledgeElementDto = super.selectOne(qw,KnowledgeElementDto.class);
        if(null == knowledgeElementDto || null == knowledgeElementDto.getSortNum()){
            return 0;
        }else{
            return  knowledgeElementDto.getSortNum() ;
        }

    }

    @Override
    public List<KnowledgeElementDto> queryTree(String subjectId){
        QueryWrapper qw=new QueryWrapper<KnowledgeElement>();
        qw.eq("pid", "0");
        qw.eq("subject_id", subjectId);
        qw.orderByAsc("sort_num");
        List<KnowledgeElementDto> list = super.selectList(qw,KnowledgeElementDto.class);
        if(list.isEmpty()){
            return new ArrayList<>();
        }
        getTree(list);
        return list;
    }

    private void getTree( List<KnowledgeElementDto> parentList){
        if(!CollectionUtils.isEmpty(parentList)){
            parentList.forEach(knowledgeElementDto -> {
                String id = knowledgeElementDto.getId();
                QueryWrapper qw=new QueryWrapper<KnowledgeElement>();
                qw.eq("pid", id);
                qw.orderByAsc("sort_num");
                List<KnowledgeElementDto> childList = super.selectList(qw,KnowledgeElementDto.class);
                if(!CollectionUtils.isEmpty(childList)){
                    knowledgeElementDto.setChilds(childList);
                    getTree(childList);
                }
            });
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteByParentId(String id) {
        boolean deleted = this.delete(id);
        if(deleted){
            String[] ids = new String[]{id};
            deleteChildNode(ids);
            deleteKnowledgeManagerRelation(ids);

        }

    }

    private void deleteChildNode(String[] pid){
        QueryWrapper<KnowledgeElement> qw = new QueryWrapper();
        qw.in("pid", pid);
        List<KnowledgeElement> knowledgeElements = super.queryByCondition(qw);
        if(!CollectionUtils.isEmpty(knowledgeElements)){
            String[] ids = knowledgeElements.stream().map(KnowledgeElement::getId).toArray(String[]::new);
            this.batchDelete(ids);
            deleteKnowledgeManagerRelation(ids);
            deleteChildNode(ids);
        }
    }

    private void deleteKnowledgeManagerRelation(String[] ids){
        QueryWrapper<KnowledgeManager> qw = new QueryWrapper();
        qw.in("knowledge_id",ids);
        List<KnowledgeManager> knowledgeManagers = knowledgeManagerService.queryByCondition(qw);
        if (!CollectionUtils.isEmpty(knowledgeManagers)){
            knowledgeManagers.forEach(knowledgeManager -> {
                knowledgeManager.setKnowledgeId("");
            });

            knowledgeManagerService.batchUpdate(knowledgeManagers);
        }
    }

    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(KnowledgeElementRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        return qw;
    }
}
